package com.xdwanj.ui.acitivity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.xdwanj.ui.test.R


class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity"

    private lateinit var jumpButton: Button

    private val MainHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Log.d(TAG, "handleMessage: 这个给主线程(UI)用")
        }
    }

    private val WorkHandler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            Log.d(TAG, "handleMessage: 这个给工作线程用的")
        }
    }


    companion object {
        val EXTRA_MAIN = "com.xdwanj.ui.test.mainInfo"

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        jumpButton = findViewById<Button>(R.id.jump_page)

        val startActivity = // 局部方法
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.data != null && it.resultCode == Activity.RESULT_OK) {
                    val stringExtra = it.data?.getStringExtra(JumpPageActivity.EXTRA_DEMO)

                    Toast.makeText(this, stringExtra, Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "error", Toast.LENGTH_SHORT).show()
                }
            }

        jumpButton.setOnClickListener {
            val intent = Intent(this, JumpPageActivity::class.java)
                .putExtra(EXTRA_MAIN, "来自主界面的信息")

            startActivity.launch(intent)
        }

        Thread {
            this.runOnUiThread {
                //这里的代码一定在主线程(UI)中
            }
        }

    }

}